import React from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable, {ProColumns} from '@ant-design/pro-table';
import util from '@/utils';
import {Button, FormInstance, message, Modal, Popconfirm, Space} from 'antd';
import Editor from '@/components/editor';
import Look from '@/components/look';
import ProCard from '@ant-design/pro-card';
import ProForm, {ProFormGroup, ProFormText, ProFormTextArea} from '@ant-design/pro-form';

import styles from '@/common/index.less';
import {articleTableColumns} from '@/common';

const type: number = 3;


const queryById = async (id: number) => {
   const loading = message.loading({
      content: '数据获取中'
   });
   const {data} = await util.request({
      url: `/article/${id}`
   });
   loading();
   return data;
};

const queryTableData = async () => {
   const {data} = await util.request({
      url: `/article/type/${type}`
   });
   return data;
};


const saveTableData = async (data: Article) => {
   const {code} = await util.request({
      url: `/article`,
      method: 'POST',
      data: {
         ...data,
         type
      }
   });
   code === 200 ? message.success('修改成功') : message.warn('修改失败');
};

const deleteTableData = async (id: number) => {
   const {code} = await util.request({
      url: `/article/${id}`,
      method: 'DELETE'
   });
   if (code === 200) {
      message.success('删除成功');
      return await queryTableData();
   } else {
      message.warn('删除失败');
   }
};


export default () => {

   const tabActiveKeyState = React.useState<string>('base');
   // const editorRef = React.useRef<{ onSubmit(): Function; setValue: Function }>();

   const selectedIdState = React.useState<number>();
   const modalState = React.useState<boolean>();

   const formRef = React.useRef<FormInstance>();

   React.useEffect(() => {
      if (tabActiveKeyState[0] === 'edit' && selectedIdState[0]) {
         queryById(selectedIdState[0]).then((res: Article) => {
            formRef.current?.setFieldsValue(res);
            // editorRef.current?.setValue(res.content);
         });
      }
   }, [tabActiveKeyState]);

   return <PageContainer

      className={styles.pageContainer}
      tabList={[{tab: '基本信息', key: 'base'}, {tab: '信息编辑', key: 'edit'}]}
      tabActiveKey={tabActiveKeyState[0]}
      extra={[
         <Button type='primary' onClick={() => {
            selectedIdState[1](0);
            tabActiveKeyState[1]('edit');
         }}>
            添加
         </Button>
      ]}
      footer={tabActiveKeyState[0] === 'edit' ? [
         <Button type='primary' onClick={async () => {
            const form = await formRef.current?.validateFields();
            saveTableData({
               ...form,
               // content: editorRef.current?.onSubmit()
            });
         }}>发布 </Button>
      ] : []}
      onTabChange={async (e) => {
         tabActiveKeyState[1](e);
      }}>

      {
         tabActiveKeyState[0] === 'base' &&
         (<ProTable
            bordered
            columns={articleTableColumns((record: Article) => {
               selectedIdState[1](record.id);
               modalState[1](true);
            }, (record: Article) => {
               selectedIdState[1](record.id);
               tabActiveKeyState[1]('edit');
            }, (record: Article) => {
               selectedIdState[1](record.id);
               record.id && deleteTableData(record.id);
            })}
            request={async () => {
               return Promise.resolve({
                  data: await queryTableData(),
                  success: true
               });
            }}
            rowKey='id'
            pagination={false}
            toolBarRender={false}
            search={false}
         />)
      }
      {
         tabActiveKeyState[0] === 'edit' &&
         <Space direction='vertical' className={styles.editTab}>
            <ProCard title='信息编辑' className={styles.form}>
               <ProForm
                  labelCol={{span: 3}}
                  layout='horizontal'
                  formRef={formRef}
                  validateMessages={{
                     required: '必填项'
                  }}
                  submitter={false}
               >
                  <ProFormText name='id' hidden />
                  <ProFormGroup>
                     <ProFormText
                        width='xl'
                        rules={[{required: true}]}
                        name='title'
                        label='文章标题'
                        placeholder='请输入标题'
                     />
                     <ProFormText
                        width='xl'
                        name='thumb'
                        label='文章缩略图'
                        placeholder='请输入图片地址'
                     />
                  </ProFormGroup>

                  <ProFormGroup>
                     <ProFormTextArea
                        fieldProps={{
                           maxLength: 140
                        }}
                        rules={[{required: true}]}
                        name='represent'
                        width='xl'
                        label='简单描述'
                        placeholder='请输入描述'
                     />
                  </ProFormGroup>
                  <ProFormGroup>
                     <ProFormText
                        rules={[{required: true}]}
                        name='content'
                        width='xl'
                        label='文章内容'
                        placeholder='word地址'
                     />
                  </ProFormGroup>
               </ProForm>
            </ProCard>
            {/*<ProCard title='内容编辑' className={styles.editor}>*/}
            {/*   <Editor editorRef={editorRef} />*/}
            {/*</ProCard>*/}
         </Space>
      }
      <Modal title='手机预览' visible={modalState[0]}
             okText='确定'
             destroyOnClose={true}
             closable={true}
             style={{top: '50px'}}
             onCancel={() => {
                modalState[1](false);
             }}
             onOk={() => {
                modalState[1](false);
             }}
             bodyStyle={{maxHeight: '420px', overflow: 'auto'}}>
         <Look id={selectedIdState[0]} />
      </Modal>
   </PageContainer>;
}
